package middle;

public class Solution_393 {

    public static void main(String[] args) {
        Solution_393 model = new Solution_393();
        System.out.println(model.validUtf8(new int[]{197,130,1})); //true
        System.out.println(model.validUtf8(new int[]{235,140,4})); //false
//
//        for (int num : new int[]{240, 162, 138, 147}) {
//            System.out.println(Integer.toBinaryString(num));
//        }
        System.out.println(model.validUtf8(new int[]{240,162,138,147,145})); // false
        System.out.println(model.validUtf8(new int[]{240,162,138,147})); // true

//        for (int num : new int[]{39,89,227,83,132,95,10,0}) {
//            System.out.println(Integer.toBinaryString(num));
//        }
        System.out.println(model.validUtf8(new int[]{39,89,227,83,132,95,10,0})); // false
        System.out.println(model.validUtf8(new int[]{228,189,160,229,165,189,13,10})); // true
    }

    private int mask = 1 << 7;
    private int other_mask_2 = mask + (1 << 6);
    private int other_mask_3 = other_mask_2 + (1 << 5);
    private int other_mask_4 = other_mask_3 + (1 << 4);
    private int other_mask_5 = other_mask_4 + (1 << 3);

    public boolean validUtf8(int[] data) {
        for (int i = 0; i < data.length; ) {
//            System.out.println(Integer.toBinaryString(data[i]));
            int count = cal_count(data[i]);
            if (count > 4) {
                return false;
            }
            int j = 1;
            while (j < count && i + j < data.length) {
                if ((data[i + j] & other_mask_2) != mask) {
                    break;
                }
                j++;
            }
            if (j != count) {
                return false;
            }
            i+=count;
        }
        return true;
    }

    private int cal_count(int num) {
        if ((num & mask) == 0) {
            return 1;
        } else if ((num & other_mask_3) == other_mask_2) {
            return 2;
        } else if ((num & other_mask_4) == other_mask_3) {
            return 3;
        } else if ((num & other_mask_5) == other_mask_4){
             return 4;
        }
        return 5;
    }
}
